<template>
  <view class="page-container">
    <u-image 
      src="/static/bg.png" 
      width="100%" 
      height="100vh" 
      mode="aspectFill"
      class="background-image"
    ></u-image>
	<view class="questions">
		<view class="question">
			{{ content }}
		</view>
		<view class="question">
			{{ questionPrompt }}
		</view>
		<!-- 添加倒计时显示 -->
	    <view class="countdown" v-if="isCountingDown">
		  剩余时间: {{ formatTime(remainingTime) }}
	    </view>
	</view>
    
    <view class="content">
      <view class="button-container">
	    <u-button type="primary" size="large" @click="hanldeBeginInterview">{{btnText}}</u-button>
	    <text class="progress-text" v-if="questions.length > 0">{{index}}/{{questions.length}}</text>
	  </view>
    </view>
  </view>
</template>




<script>
	
	import { getQuestions, genReport } from '@/api/interview/answer';
	
	export default {
		data() {
			return {
				questions: [],
				// 当前正在作答的题目
				index: 0,
				content: '请点击“开始面试”按钮开始答题',
				questionPrompt: '',
				btnText: '开始面试',
				recordManager: null,
				// 录音文件的地址
				recordFilePath: null,
				// 新增计时器相关变量
				timer: null,
				remainingTime: 300, // 剩余时间（秒），5分钟=300秒
				isCountingDown: false // 是否正在倒计时
			};
		},
		methods:{
			// 根据面试记录加载面试问题
			async loadQuestions(){
				let recordId = uni.getStorageSync("interviewRecord");
				// 发送请求到后端
				const res = await getQuestions(recordId)
				this.questions = res.data
			},
			// 开始面试
			hanldeBeginInterview(){
				// =================录音的逻辑=================
				// 第一次点击
				if(this.index == 0){
					// 开启下一次的录音
					this.btnText = '下一题'
					this.showQuestion(this.index);
					this.recordManager.start({
						format: 'mp3',
						duration: 300000,
					})
					// 开始倒计时
					this.startCountdown();
					this.index++;
				}else{
					// 结束上一次的录音 
					this.recordManager.stop()
					// 停止倒计时
					this.stopCountdown();
				}
				
			},
			showQuestion(index){
				if(index < this.questions.length){
					this.content = this.questions[index].content;
					this.questionPrompt = this.questions[index].questionPrompt;
				}
			},
			// 上传录音
			uploadRecord(){
				uni.uploadFile({
					url: 'http://localhost:8080/interview/answer/handleAnswer',
					filePath: this.recordFilePath.file,
					name: 'file',
					formData: {
						questionId: this.recordFilePath.questionId,
					},
					success: (res) => {
						console.log('res',res)
					}
				})
			},
			// 格式化时间显示（秒 -> 00:00）
			formatTime(seconds) {
			    const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
			    const secs = (seconds % 60).toString().padStart(2, '0');
			    return `${mins}:${secs}`;
			},
			// 开始倒计时
			startCountdown() {
			    this.isCountingDown = true;
			    this.timer = setInterval(() => {
			      if (this.remainingTime > 0) {
			        this.remainingTime--;
			      } else {
			        // 时间到，自动下一题
			        this.handleTimeout();
			      }
			    }, 1000);
			},
			  
			// 停止倒计时
			stopCountdown() {
			    if (this.timer) {
			      clearInterval(this.timer);
			      this.timer = null;
			      this.isCountingDown = false;
			    }
			},
			// 处理超时
			handleTimeout() {
			    this.stopCountdown();
			    // 停止录音
			    if (this.recordManager) {
			      this.recordManager.stop();
			    }
			    // 自动切换到下一题
			    if (this.index < this.questions.length) {
			      this.index++;
			      this.showQuestion(this.index);
			      this.remainingTime = 300; // 重置为5分钟
			      this.startCountdown();
			    }
			},
		},
		onLoad() {
			this.loadQuestions()
			this.recordManager = uni.getRecorderManager();
			// 录音结束的时候
			this.recordManager.onStop((res) => {
				// 保存录音文件
				this.recordFilePath = {
					file: res.tempFilePath,
					questionId: this.questions[this.index-1].id  // 结束的上一次录音，所以是this.index-1
				}
				// 上传录音文件
				this.uploadRecord()
				// =====================控制按钮显示的内容=======================
				if(this.index > 0 && this.index < this.questions.length-1){
					// 下一题下一题....
					this.btnText = '下一题'
				}else{
					this.btnText = '结束面试'
				}
				
				// =====================展示当前题==========================
				this.showQuestion(this.index);
				
				// 最后一次点击
				if(this.index >= this.questions.length){
					// 调用接口：生成面试评价
					let recordId = uni.getStorageSync("interviewRecord");
					// 异步请求生成评价
					genReport(recordId)
					// 页面跳转
					uni.navigateTo({
						url:'/pages/interview/interview'
					})
				}else{
					// 开启下一次的录音
					this.recordManager.start({
						duration: 300000,
						format: 'mp3'
					})
					// 开始新题目倒计时
					this.remainingTime = 300; // 重置为5分钟
					this.startCountdown();
				}
				
				if(this.index < this.questions.length){
					this.index++
				}
				
				
			})
		},
		onUnload() {
		  this.stopCountdown();
		},
	}
</script>
<style lang="scss" scoped>
.page-container {
  position: relative;
  width: 100%;
  height: 100vh;
}

.background-image {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
}

.content {
  position: fixed;
  bottom: 150rpx;
  left: 125rpx;
  z-index: 1;
  width: 500rpx;
  
  .button-container {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20rpx;
    
    .progress-text {
      font-size: 28rpx;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.5);
      padding: 8rpx 16rpx;
      border-radius: 8rpx;
    }
  }
}
.questions {
  position: fixed;
  z-index: 1;
  bottom: 400rpx; /* 增加与按钮的距离 */
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  max-width: 600rpx;
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .countdown {
      font-size: 28rpx;
      color: #ff0000;
      text-align: center;
      margin-top: 20rpx;
      font-weight: bold;
    }
}
 
.question {
  font-size: 32rpx;
  line-height: 1.6;
  color: #333;
  margin-bottom: 20rpx;
  text-align: center;
  
  &:first-child {
    font-weight: bold;
    font-size: 36rpx;
    margin-bottom: 15rpx;
  }
}
</style>
